package com.hckjsec.common.skp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.dongliu.requests.RawResponse;
import net.dongliu.requests.Requests;

import java.io.*;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class HbRequestKit {
    public static JSONObject request(String url, String publickey, String privatekey, String json,String jgbm,String fyjsbh)
            throws UnsupportedEncodingException {
        Calendar calendar = Calendar.getInstance();
        String path="D://spkpxt//"+jgbm+"//" + calendar.get(Calendar.YEAR) + "//" + (calendar.get(Calendar.MONTH)+1) + "//" + calendar.get(Calendar.DATE) + "//";
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        path=path+fyjsbh+".txt";
        System.out.println("------"+jgbm+"----------"+fyjsbh+"------");
        write2file("请求的文明:" + json,path);
        JSONObject requestjsonobj = JSON.parseObject(json);
        if (requestjsonobj.containsKey("input")) {
            String inputstr = requestjsonobj.getJSONObject("input").toJSONString();
            String inputmi = HCAESUtil.encrypt(inputstr, privatekey);
            write2file("input内容加密:" + inputmi,path);
            requestjsonobj.put("input", inputmi);
        }

        String requestjson = HCAESUtil.encrypt(requestjsonobj.toJSONString(), publickey);
        write2file("报文加密:" + requestjson,path);
        Map<String, String> reqbody = new HashMap<String, String>();
        reqbody.put("json", URLEncoder.encode(requestjson, "UTF-8"));
        // reqbody.put("debug", "true");
        RawResponse response = Requests.post(url).body(reqbody).verify(false).timeout(60000).send();
        String responsetext = response.readToText();
        write2file("接受返回报文：" + responsetext,path);
        JSONObject ret = JSON.parseObject(responsetext);
        String rawdata = ret.getString("data");
        if (rawdata != null && !rawdata.equals("")) {
            System.out.println(rawdata);
            String outdata = HCAESUtil.decrypt(rawdata, privatekey);
            write2file("解密：" + outdata,path);
            Object jsonobj = JSON.parse(outdata);
            ret.put("data", jsonobj);
        }
        return ret;
    }

    private static void write2file(String content,String path){
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(new File(path),true));
            writer.write(content + "\r\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
